<template>
  <div class="equipment">
    <!-- 地图容器 -->
    <div id="container"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getequipmentlist } from '@/api/echarts';

let map = null;
export default {
  name: 'index',
  props: {
    lat: {
      type: Number,
      required: true,
      default: 1, // 默认值
    },
    lng: {
      type: Number,
      required: true,
      default: 1, // 默认值
    },
    zoom: {
      type: Number,
      required: true,
      default: 1, // 默认值
    }
  },
  data() {
    return {};
  },
  mounted() {
    // DOM初始化完成进行地图初始化
    console.log('Received lat:', this.lat);
    console.log('Received lng:', this.lng);
    this.initMap(this.lat, this.lng, this.zoom);
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Scale', 'AMap.Marker', 'AMap.InfoWindow', 'AMap.MarkerCluster'],
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        } // 需要使用的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        map = new AMap.Map("container", { // 设置地图容器id
          viewMode: "2D", // 是否为3D地图模式
          terrain: false, // 开启地形图
          zoom: this.zoom, // 初始化地图级别
          center: [this.lng, this.lat], // 初始化地图中心点位置
          mapStyle: "amap://styles/blue",
        });
        this.aMapUiLoad();
      }).catch(e => {
        console.log('高德地图加载错误提示${e}'); // 加载错误提示
      });
    },
    // 区划聚合+海量点展示
    initPage(DistrictCluster, PointSimplifier) {
      var pointSimplifierIns = new PointSimplifier({
        map: map, // 所属的地图实例
        autoSetFitView: false, // 禁止自动更新地图视野
        zIndex: 110,
        getPosition: function (item) {
          if (!item) {
            return null;
          }
          return item.lnglat;
        },
        getHoverTitle: function (dataItem, idx) {
          return <div style="height: 12vh;width: 16vw;background-color:#FFFFFF;margin:0;padding:0;z-index:9999999">
                    <h2>第${idx}台设备</h2>
                    <p>
                       设备简介
                    </p>
                  </div>;
        },
        renderOptions: {
          pointStyle: {
            width: 6,
            height: 6,
            fillStyle: 'rgba(153, 0, 153, 0.38)'
          },
          hoverTitleStyle: {
            position: 'top'
          }
        }
      });

      var distCluster = new DistrictCluster({
        zIndex: 100,
        map: map, // 所属的地图实例
        getPosition: function (item) {
          if (!item) {
            return null;
          }
          return item.lnglat;
        },
        renderOptions: {
          getFeatureStyle: function (feature, dataItems) {
            return {
              fillStyle: 'rgba(0, 115, 153, 0.6)', // 高亮显示
              strokeStyle: 'rgba(0, 0, 0, 0.5)', // 边框颜色
              lineWidth: 1
            };
          },
          featureStyle: {
            fillStyle: 'rgba(0, 115, 153, 0.6)', // 高亮显示
            strokeStyle: 'rgba(0, 0, 0, 0.5)', // 边框颜色
            lineWidth: 1,
            hoverOptions: {
              fillStyle: 'rgba(153, 204, 255, 0.5)', // 浅青色调
              lineWidth: 5,
              strokeStyle: 'rgb(255, 102, 0)' // 橙色调
            }
          },
          featureEventSupport: true,
          clusterMarkerEventSupport: true,
          clusterMarkerEventNames: ['click', 'rightclick', 'mouseover', 'mouseout']
        }
      });

      window.distCluster = distCluster;

      function updateMarkerVisibility() {
        // 获取所有标记
        const markers = document.querySelectorAll('.amap-ui-district-cluster-marker, .amap-ui-district-cluster-marker.level_city.adcode_211100.descendant_of_100000.descendant_of_210000.child_of_210000',' amap - ui - district - cluster - marker level_district adcode_211002 descendant_of_100000 descendant_of_210000 descendant_of_211000 child_of_211000');

        // 先隐藏所有标记
        markers.forEach(marker => {
          marker.style.display = 'none';
        });

        // 然后根据计数判断大于0的标记再显示
        markers.forEach(marker => {
          const countText = marker.querySelector('.amap-ui-district-cluster-marker-body').textContent;
          if (parseInt(countText, 10) > 0) {
            marker.style.display = '';
          }
        });
      }


      function refresh() {
        var zoom = map.getZoom();
        var pointStyle = pointSimplifierIns.getRenderOptions().pointStyle;
        pointStyle.width = pointStyle.height = 2 * Math.pow(1.2, zoom - 3);
        updateMarkerVisibility(); // 确保在每次缩放结束后更新标记的可见性
      }

      map.on('zoomend', function () {
        refresh();
      });

      refresh(); // 初始调用以确保标记的正确显示

      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      getequipmentlist({ limit: 10000 }).then(res => {
  if (res.code === 0) {
    let data = res.msg;
    let transformedData = data
      .filter(item => item.count !== 0) // 过滤掉 count 为 0 的数据
      .map(item => {
        let lng = parseFloat(item.lng);
        let lat = parseFloat(item.lat);
        
        // 打印经纬度
        console.log(`Longitude: ${lng}, Latitude: ${lat}`);
        
        return {
          lnglat: [lng, lat],
          addr: item.addr,
          addrDetail: item.addrDetail,
          addtime: item.addtime,
          agreement: item.agreement,
          detail: item.detail,
          equipmentNo: item.equipmentNo,
          isWorkorder: item.iSWorkorder,
          id: item.id,
          mainBind: item.mainBind,
          status: item.status,
          type: item.type,
          count: item.count
        };
      });

    distCluster.setData(transformedData); // 设置 distCluster 的数据为处理后的数组
    pointSimplifierIns.setData(transformedData); // 设置 pointSimplifierIns 的数据为处理后的数组
  } else {
    console.error('API 返回错误:', res);
  }
}).catch(error => {
  console.error('请求出错:', error);
}).finally(() => {
  loading.close();
});

    },
    // 加载(区划聚合+海量点展示)、行政区划相关组件
    aMapUiLoad() {
      AMapUI.load(['ui/geo/DistrictCluster', 'ui/misc/PointSimplifier', 'lib/$'], (DistrictCluster, PointSimplifier) => {
        // 启动页面
        this.initPage(DistrictCluster, PointSimplifier);

        // 确保地图和所有标记完全加载后再隐藏标记盒子
        setTimeout(() => {
          const markers = document.querySelectorAll('.amap-ui-district-cluster-marker','amap-ui-district-cluster-marker level_city adcode_210400 descendant_of_100000 descendant_of_210000 child_of_210000','');
          markers.forEach(marker => {
            const countText = marker.querySelector('.amap-ui-district-cluster-marker-body').textContent;
            if (parseInt(countText, 10) === 0) {
              marker.style.display = 'none';
            }
          });
        }, 1000); // 1000ms 延迟可以根据需要调整
      });
    }
  }
};
</script>

<style lang="scss">
.equipment {
  #container {
    width: 100%;
    height: 120vh;
  }

  .amap-ui-district-cluster-region {
    background-color: rgba(0, 115, 153, 0.6) !important; // 高亮显示中国地图
  }
}
</style>